#!/usr/bin/python
# -*- coding: UTF-8 -*-

from datetime import datetime
import os
import shutil
import csv
import sys

import zipfile
import os
import subprocess
import threading
import re

import binascii
import optparse

import datetime
import time
import shutil

from xml.etree.ElementTree import ElementTree
import struct

import json

from PIL import Image, ImageTk

import psutil

import matplotlib 
import numpy as np
import matplotlib as mpl
import datetime
from matplotlib.widgets import Button,RadioButtons
from matplotlib.widgets import CheckButtons

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

import codecs

'''
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position

解决方法

import codecs

fr = open('test.txt')

改为如下即可解决问题：

fr= codecs.open('test.txt', 'r',encoding= u'utf-8',errors='ignore')

'''

def analyse(filename):
    #------------
    part_battery_capacity = host_subplot(111, axes_class=AA.Axes)
    plt.subplots_adjust(right=0.75)

    part_battery_voltage_now = part_battery_capacity.twinx()
    part_battery_temp = part_battery_capacity.twinx()
    part_battery_status = part_battery_capacity.twinx()
    part_battery_chg = part_battery_capacity.twinx()
    #par2 = part_battery_capacity.twinx()
    #------------

    battery_time=""
    battery_capacity=""
    battery_voltage_now=""
    battery_temp=""
    battery_health=""
    battery_status=""
    battery_chg=""

    list_battery_time = []
    list_battery_capacity = []
    list_battery_voltage_now = []
    list_battery_temp = []
    list_battery_health = []
    list_battery_status = []
    list_battery_chg = []

    #fin = open(filename, 'r')
    fin = codecs.open(filename, 'r',encoding= u'utf-8',errors='ignore')
    fout = open('kmsg.csv', 'w')


    for line in fin.readlines():
        line = line.strip()                             #remove tab and space
        if re.match('.+healthd:\ battery', line):
            print ("%s" % (line) + "\t\t\t\tline:%s" %sys._getframe().f_lineno)

            # 130425.299122
            # <14>[114934.753885]
            # 964[12-26 17:47:31.107] <12>[29464.493399] c0 healthd: battery l=100 v=4186 t=37.6
            # [10152.970317] c0 healthd: battery l=1 v=3376 t=27.8 h=2 st=3 chg=
            # 873[03-13 04:37:28.278] <12>[ 9882.248085] c0 healthd: battery l=2 v=3383 t=28.5 h=2 st=3 chg=
            var = re.search('(\>|\[|.\>\[).+[0-9]{1,6}\.[0-9]{1,6}\].' , line).group()
            print (var + "\t\t\t\tline:%s" %sys._getframe().f_lineno)
            battery_time = float(re.search('[0-9]{1,6}\.[0-9]{4,6}' , var).group())
            #battery_time = battery_time1 * 1000000
            print (str(battery_time) + "\t\t\t\tline:%s" %sys._getframe().f_lineno)

            list_battery_time.append(battery_time)

            # l=37
            var = re.search('l=[0-9]{1,3}' , line).group()
            #print (var)
            battery_capacity = int(re.search('[0-9]{1,3}' , var).group())
            #print (battery_capacity)

            list_battery_capacity.append(battery_capacity)

            # v=3769
            var = re.search('v=[0-9]{1,4}' , line).group()
            #print (var)
            battery_voltage_now = int(re.search('[0-9]{1,4}' , var).group())
            #print (battery_voltage_now)

            list_battery_voltage_now.append(battery_voltage_now)

            # t=24.0
            var = re.search('t=[0-9]{1,3}.[0-9]{1,3}' , line).group()
            #print (var)
            battery_temp = float(re.search('[0-9]{1,3}.[0-9]{1,3}' , var).group())
            #print (battery_temp)

            list_battery_temp.append(battery_temp)

            # h=1
            var = re.search('h=[0-9]{1,1}' , line).group()
            #print (var)
            battery_health = int(re.search('[0-9]{1,1}' , var).group())
            #print (battery_health)

            list_battery_health.append(battery_health)

            # st=3
            var = re.search('st=[0-9]{1,1}' , line).group()
            #print (var)
            battery_status = int(re.search('[0-9]{1,1}' , var).group())
            #print (battery_status)

            list_battery_status.append(battery_status)

            # chg=
            var = re.search('chg=[a-z]{0,3}' , line).group()
            #print (var)
            battery_chg = re.search('[a-z]{0,3}$' , var).group()
            #print (battery_chg)
            # null a u w au
            #   0  1 2 3 4
            if battery_chg == 'a' :
                list_battery_chg.append(1)
            elif battery_chg == 'u' :
                list_battery_chg.append(2)
            elif battery_chg == 'w' :
                list_battery_chg.append(3)
            elif battery_chg == 'au' :
                list_battery_chg.append(4)
            else :
                list_battery_chg.append(0)

            fout.write(str(battery_time) + "," + str(battery_capacity) + "," + str(battery_voltage_now) + "," + str(battery_temp) + "," + str(battery_status) + "," + battery_chg + '\n')
    # [87340.173774] healthd: battery l=37 v=3769 t=24.0 h=1 st=3 c=73 fc=0 cc=4 chg=



    fout.close()
    fin.close()


    #print ("list_battery_time = " + str(len(list_battery_time)))
    #print ("list_battery_capacity = " + str(len(list_battery_capacity)))
    #print ("list_battery_voltage_now = " + str(len(list_battery_voltage_now)))
    #print ("list_battery_temp = " + str(len(list_battery_temp)))
    #print ("list_battery_health = " + str(len(list_battery_health)))
    #print ("list_battery_status = " + str(len(list_battery_status)))
    #print ("list_battery_chg = " + str(len(list_battery_chg)))

    p1, = part_battery_capacity.plot(list_battery_time, list_battery_capacity, label="capacity")
    p2, = part_battery_voltage_now.plot(list_battery_time, list_battery_voltage_now, label="voltage")
    p3, = part_battery_temp.plot(list_battery_time, list_battery_temp, label="temp")
    p4, = part_battery_status.plot(list_battery_time, list_battery_status, label="status", marker='.')
    p7, = part_battery_chg.plot(list_battery_time, list_battery_chg, label="chg")
    #p3, = par2.plot(list_battery_time, battery_capacity, label="Velocity")


    offset = 50
    new_fixed_axis = part_battery_temp.get_grid_helper().new_fixed_axis
    part_battery_temp.axis["right"] = new_fixed_axis(loc="right", axes=part_battery_temp, offset=(offset, 10))

    offset = 90
    new_fixed_axis = part_battery_status.get_grid_helper().new_fixed_axis
    part_battery_status.axis["right"] = new_fixed_axis(loc="right", axes=part_battery_status, offset=(offset, 10))

    offset = 210
    new_fixed_axis = part_battery_chg.get_grid_helper().new_fixed_axis
    part_battery_chg.axis["right"] = new_fixed_axis(loc="right", axes=part_battery_chg, offset=(offset, 10))

    part_battery_voltage_now.axis["right"].toggle(all=True)
    part_battery_temp.axis["right"].toggle(all=True)
    part_battery_status.axis["right"].toggle(all=True)
    part_battery_chg.axis["right"].toggle(all=True)

    part_battery_capacity.set_ylim(0, 102)
    part_battery_status.set_ylim(-1, 6)
    part_battery_chg.set_ylim(-1, 5)  # limit y
    #part_battery_capacity.set_xlim(0, 2)  # limit x
    #part_battery_capacity.set_ylim(0, 2)  # limit y

    part_battery_capacity.set_xlabel("Times")
    part_battery_capacity.set_ylabel("capacity")
    #part_battery_capacity.invert_yaxis() # invert y

    part_battery_voltage_now.set_ylabel("voltage")
    part_battery_temp.set_ylabel("temp")
    part_battery_status.set_ylabel("status 1:Unknown; 2:Charging; 3:Discharging; 4:Not charging; 5:full")
    part_battery_chg.set_ylabel("chg 0:null 1:a 2:u 3:w 4:au")

    #part_battery_voltage_now.set_ylim(0, 4)
    #part_battery_temp.set_ylim(1, 30)

    part_battery_capacity.legend()

    part_battery_capacity.axis["left"].label.set_color(p1.get_color())
    part_battery_voltage_now.axis["right"].label.set_color(p2.get_color())
    part_battery_temp.axis["right"].label.set_color(p3.get_color())
    part_battery_status.axis["right"].label.set_color(p4.get_color())
    part_battery_chg.axis["right"].label.set_color(p7.get_color())

    #part_battery_capacity.yaxis.grid(which="both", color='r', linestyle='-', linewidth=2)
    #part_battery_capacity.xaxis.grid(which="minor", color='r', linestyle='-', linewidth=2)
    plt.grid()
    plt.draw()
    #plt.show()

    lines = [p1, p2, p3, p4, p7]
    rax = plt.axes([0.7, 0.9, 0.1, 0.1])
    labels = [str(line.get_label()) for line in lines]
    visibility = [line.get_visible() for line in lines]
    check = CheckButtons(rax, labels, visibility)

    def func(label):
        index = labels.index(label)
        lines[index].set_visible(not lines[index].get_visible())
        plt.draw()

    check.on_clicked(func)


    plt.show()
if __name__ == '__main__':

    usage=" \n \
  qm215: \n \
    egrep \".+healthd:\ battery\" kernel.log > k.log \n \
    python analyse_healthd.py -f <kernel log> \n \
    \n \
  sprd: \n \
    egrep \".+healthd:\ battery\" kernel.log > k.log \n \
    python analyse_healthd_sprd.py -f <kernel log> \n \
    \n \
  All(qm215 sprd 8909): \n \
    egrep \"power_supply_update|BatteryBroadcastReceiver\" * -r | sed -r 's/main.+\.log://g'| sed -r 's/bootloglogcat_.+\.log://g'| sort.exe > v.log \n \
    python analyse_vm_bms.py -f <main log> \n \
    "  #
    parser=optparse.OptionParser(usage)  #
    parser.add_option('-f',dest='File',type='string',help='target host')
    (options,args)=parser.parse_args()

    print(options.File)

    if options.File :
        analyse(options.File)
    else :
        print (usage)





